% Fit a line, and report the slope intercept and r^2. Include error bars.
function [m, b, r2] = FitLine(x, y)
    %do fit
    %fctn = fittype('m*x + b');
    if size(x, 2) > size(x, 1)
        x = x';
    end
    if size(y, 2) > size(y, 1)
        y = y';
    end
    
    try
    
    [fitresult, fitgoodness] = fit(x, y, 'poly1');
    
    %extract error bars.
    level = 2*tcdf(-1, fitgoodness.dfe);
    confInterval = confint(fitresult, 1-level);
    mRange = (confInterval(2, 1) - confInterval(1, 1)) / 2;
    bRange = (confInterval(2, 2) - confInterval(1, 2)) / 2;
    
    %report values.
    m = [fitresult.p1, mRange];
    b = [fitresult.p2, bRange];
    r2 = fitgoodness.rsquare;
    
    catch
        m = [NaN, NaN];
        b = m;
        r2 = NaN;
    end
    
%     figure(11);
%     hold off;
%     plot(x, y, 'o');
%     hold all;
%     plot(x, fitresult(x));
%     pause(0.25);
end